<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router';
import courseService from '@/services/courseService.js';
import { userManager } from '@/utils/user'

const router = useRouter();

const courses = ref([])
const currentIndex = ref(0)
const visibleCourses = ref(2)
const isLoading = ref(true)
const message = ref('')
const serverUrl = userManager.getServerUrl()
const role = ref(null)

const goToCourseDetail = (courseId) => {
  if (courseId) {
    router.push(`/course/${courseId}`); // 功能保持不变
  }
};

onMounted(async () => {
  const currentUser = userManager.getUserInfo()

  if (!currentUser) {
    isLoading.value = false
    message.value = '您尚未登录，请登录后查看我的课程。'
    return
  }

  try {
    role.value = userManager.getRole() // 获取用户角色
    const userId = userManager.getUserId()
    let response

    if (role.value === 'teacher') { // 根据角色判断调用哪个服务
      response = await courseService.getCourseList({teacherId: userId, page: 1, size: 10})
    } else {
      response = await courseService.getSelectedCoursesByUserId(userId, {page: 1, size: 10})
    }

    if (response.success && response.data.records && response.data.records.length > 0) {
      courses.value = response.data.records.map(course => {
        const mappedCourse = {
          id: course.id,
          title: course.name,
          cover: course.image,
        };
        if (role.value === 'student') {
          mappedCourse.instructor = course.teacherName || '未知讲师';
          mappedCourse.progress = Math.round(course.progress_percent || 0);
          mappedCourse.lastStudy = course.last_study || '无学习记录';
        } else { // 教师

          mappedCourse.instructor = course.teacherUsername || '未知讲师';
          mappedCourse.progress = 100;
          mappedCourse.lastStudy = '您是课程的创建者';
        }
        return mappedCourse;
      })
    } else {
      message.value = '您还没有相关的课程，快去创建或加入吧！'
    }
  } catch (error) {
    console.error('获取我的课程失败:', error)
    message.value = '加载课程失败，请稍后重试。'
  } finally {
    isLoading.value = false
  }
  updateVisibleCourses()
  window.addEventListener('resize', updateVisibleCourses)
})
onUnmounted(() => {
  window.removeEventListener('resize', updateVisibleCourses)
})

  const updateVisibleCourses = () => {
  if (window.innerWidth < 768) {
    visibleCourses.value = 1
  } else {
    visibleCourses.value = 2
  }
}

const prevCourse = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
  } else {
    currentIndex.value = Math.max(0, courses.value.length - visibleCourses.value)
  }
}

const nextCourse = () => {
  if (currentIndex.value < courses.value.length - visibleCourses.value) {
    currentIndex.value++
  } else {
    currentIndex.value = 0
  }
}
</script>

<template>
  <div class="my-course-container">
    <div class="my-course-header">
      <h2>我的课程</h2>
    </div>
    <div class="my-course-content">
      <div v-if="isLoading" class="status-message">
        正在加载您的课程...
      </div>
      <div v-else-if="courses.length === 0" class="status-message">
        {{ message }}
      </div>
      <div v-else class="course-carousel">
        <button class="arrow-btn prev" @click="prevCourse" v-if="courses.length > visibleCourses">
          <svg viewBox="0 0 24 24" width="24" height="24"><path d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z" fill="currentColor"/></svg>
        </button>
        <div class="course-viewport">
          <div class="course-list" :style="{ transform: `translateX(-${currentIndex * (100 / visibleCourses)}%)` }">
            <div class="course-card" v-for="course in courses" :key="course.id" :style="{ width: `${100 / visibleCourses}%` }">
              <div class="course-cover">
                <img :src="course.cover" :alt="course.title">
              </div>
              <div class="course-info">
                <h3 class="course-title">{{ course.title }}</h3>
                <p class="course-instructor">讲师: {{ course.instructor }}</p>
                <div class="progress-container">
                  <span class="progress-text">学习进度: {{ course.progress }}%</span>
                  <div class="progress-bar"><div class="progress-fill" :style="{ width: course.progress + '%' }"></div></div>
                </div>
                <p class="last-study">上次学习: {{ course.lastStudy }}</p>
                <button class="continue-btn" @click="goToCourseDetail(course.id)">继续学习</button>
              </div>
            </div>
          </div>
        </div>
        <button class="arrow-btn next" @click="nextCourse" v-if="courses.length > visibleCourses">
          <svg viewBox="0 0 24 24" width="24" height="24"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z" fill="currentColor"/></svg>
        </button>
      </div>
      <div class="carousel-dots" v-if="!isLoading && courses.length > 0 && courses.length > visibleCourses">
        <span
            v-for="(dot, index) in Math.max(1, courses.length - visibleCourses + 1)"
            :key="index"
            :class="{ active: index === currentIndex }"
            @click="currentIndex = index"
        ></span>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 样式保持不变 */
.my-course-container {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.my-course-header {
  background-color: #04cff3; /* 鲜黄色 */
  color: #333;
  padding: 12px 20px;
}

.my-course-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.my-course-content {
  background-color: #fff;
  padding: 20px;
}

.status-message {
  text-align: center;
  color: #888;
  font-size: 16px;
  padding: 60px 20px;
}

.course-carousel {
  display: flex;
  align-items: center;
  position: relative;
}

.course-viewport {
  width: 100%;
  overflow: hidden;
}

.course-list {
  display: flex;
  transition: transform 0.5s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.course-card {
  flex-shrink: 0;
  box-sizing: border-box;
  padding: 0 10px; /* 卡片之间的间距 */
  display: flex;
  background-color: #f9fafb;
  border-radius: 10px;
  border: 1px solid #f0f2f5;
  margin: 5px;
  overflow: hidden;
}

.course-cover {
  width: 45%;
  flex-shrink: 0;
}

.course-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.course-info {
  width: 55%;
  padding: 15px;
  display: flex;
  flex-direction: column;
}

.course-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.course-instructor {
  margin: 0 0 12px 0;
  font-size: 13px;
  color: #777;
}

.progress-container {
  margin-bottom: 12px;
}

.progress-text {
  display: block;
  font-size: 12px;
  color: #777;
  margin-bottom: 5px;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background-color: #e9ecef;
  border-radius: 3px;
}

.progress-fill {
  height: 100%;
  background-color: #28a745; /* 绿色进度条 */
  border-radius: 3px;
}

.last-study {
  margin: 0 0 15px 0;
  font-size: 12px;
  color: #aaa;
}

.continue-btn {
  padding: 8px 12px;
  background-color: #ffc107;
  color: #333;
  border: none;
  border-radius: 5px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  align-self: flex-start;
  margin-top: auto;
  transition: background-color 0.2s;
}

.continue-btn:hover {
  background-color: #e0a800;
}

.arrow-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 36px;
  height: 36px;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid #eee;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  color: #555;
}
.arrow-btn:hover {
  background-color: #fff;
  color: #000;
}
.arrow-btn.prev { left: -18px; }
.arrow-btn.next { right: -18px; }

.carousel-dots {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}
.carousel-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ddd;
  margin: 0 4px;
  cursor: pointer;
}
.carousel-dots span.active {
  background-color: #ffc107;
}
</style>
